import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  type Config,
  addConfig,
  deleteConfig,
  getConfigList,
  updateConfig,
  clearConfigCache
} from "@/api/system";
import { addDialog } from "@/components/ReDialog";
import { ref, onMounted, h, reactive } from "vue";
import { DictTag } from "@/components/ReDict";

export function useConfig() {
  const form = reactive<Config>({
    key: null,
    type: null,
    state: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const columns: TableColumnList = [
    {
      label: "配置名称",
      prop: "key",
      width: 250
    },
    {
      label: "配置内容",
      prop: "value",
      width: 200,
      cellRenderer({ row, props }) {
        if (row.dict) {
          return (
            <DictTag size={props.size} value={row.value} code={row.dict} text />
          );
        } else {
          return row.value;
        }
      }
    },
    {
      label: "配置说明",
      prop: "desc"
    },
    {
      label: "状态",
      prop: "state",
      width: 100,
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.state} code="State" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function onSearch() {
    getConfigList(form)
      .then(data => {
        dataList.value = data; // 处理成树结构
      })
      .catch(err => {
        message(`配置查询失败:${err.message}`, {
          type: "error"
        });
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false;
        }, 500);
      });
  }

  function openDialog(title = "新增", row?: Config) {
    addDialog({
      title: `${title}配置`,
      props: {
        formInline: {
          id: row?.id ?? "",
          key: row?.key ?? "",
          value: row?.value ?? "",
          desc: row?.desc ?? "",
          dict: row?.dict ?? undefined,
          state: row?.state ?? true,
          type: row?.type ?? form.type
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function add() {
          addConfig(curData)
            .then(() => {
              message("配置新增成功", {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`配置新增失败:${err}`, {
                type: "error"
              });
            });
        }
        function update() {
          updateConfig(curData)
            .then(() => {
              message("配置更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`配置更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function handleDelete(row: Config) {
    deleteConfig(row.id)
      .then(() => {
        message("配置删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`配置删除失败:${err}`, { type: "error" });
      });
  }

  function clearCache() {
    clearConfigCache()
      .then(() => {
        message("缓存刷新成功", { type: "success" });
      })
      .catch(err => {
        message(`缓存刷新失败:${err}`, { type: "error" });
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    resetForm,
    /** 新增、编辑配置 */
    openDialog,
    /** 删除配置 */
    handleDelete,
    clearCache
  };
}
